﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace LowCoding.Common
{
    /// <summary>
    /// http上下文
    /// </summary>
    public class HttpContext
    {
        private static IHostingEnvironment _hostEnviroment;
        private static IHttpContextAccessor _contextAccessor;

        public static string WebPath => _hostEnviroment.WebRootPath;

        /// <summary>
        /// 当前上下文
        /// </summary>
        public static Microsoft.AspNetCore.Http.HttpContext Current => _contextAccessor.HttpContext;

        public static string MapPath(string path)
        {
            return Path.Combine(_hostEnviroment.WebRootPath, path);
        }

        public static void Configure(IHostingEnvironment hostEnviroment)
        {
            _hostEnviroment = hostEnviroment;
        }

        public static void Configure(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }
    }

    public static class StaticHttpContextExtensions
    {
        public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app)
        {
            HttpContext.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
            HttpContext.Configure(app.ApplicationServices.GetRequiredService<IHostingEnvironment>());
            return app;
        }
    }
}